package com.example.controller;

import com.example.pojo.Comment;
import com.example.pojo.User;
import com.example.pojo.Work;
import com.example.service.UserService;
import com.example.utils.FileUploadUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;

@RestController
@CrossOrigin(origins = "http://localhost:5173")  // 添加到 Controller 类上
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    private UserService userService;

    //获取所有用户
    @GetMapping("/all")
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }

    // 注册用户
    @PostMapping("/register")
    public String register(@RequestBody User user) {
        userService.register(user);
        return "注册成功！";
    }

    // 登录
    @PostMapping("/login")
    public User login(@RequestParam String username, @RequestParam String password) {
        return userService.login(username, password);
    }
//    @Value("${file.upload-dir}")
//    private String UploadDir;

    // 更新用户信息
    @PutMapping("/info/{userId}")
    public String updateUserInfo(@PathVariable Integer userId, @RequestBody User user) {
        User currentUser = userService.getUserById(userId);
        if(currentUser != null) {
            if(user.getAvatarUrl() == null){
                user.setAvatarUrl(currentUser.getAvatarUrl());
            }
        }
        user.setId(userId);
        try{
            userService.updateUser(user);
            return "用户信息更新成功！";
        } catch (Exception e) {
            e.printStackTrace();
            return "更新失败！";
        }
    }
    // 更新用户头像
    @PutMapping("/avatar/{userId}")
    public String updateUserAvatar(@PathVariable Integer userId, @RequestParam("avatar") MultipartFile avatar) {
        try {
            if(!avatar.isEmpty()) {
                String avatarPath = FileUploadUtils.processFileUpload(avatar);
                User user = userService.getUserById(userId); // 假设有一个根据 ID 查找用户的方法
                if(user != null) {
                    user.setAvatarUrl(avatarPath);
                    userService.updateUser(user);
                    return "用户头像更新成功！";
                } else {
                    return "用户不存在！";
                }
            } else {
                return "上传的头像为空！";
        }
    } catch (Exception e) {
        e.printStackTrace();
        return "上传失败！";
        }
    }

    // 处理头像上传
//    private String processAvatarUpload(MultipartFile avatar) throws Exception {
//        Path uploadPath = Paths.get(UploadDir);
//        if (!Files.exists(uploadPath)) {
//            Files.createDirectory(uploadPath);
//        }
//        // 获取文件名并构建目标路径
//        String fileName = avatar.getOriginalFilename();
//        Path filePath = uploadPath.resolve(fileName);
//
//        // 将文件保存到指定路径
//        Files.copy(avatar.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
//
//        // 返回存储的文件路径或URL
//        return filePath.toString();
//    }
    //退出登录
    @PostMapping("/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return "退出登录成功！";
    }

    // 获取用户信息
    @GetMapping("/info/{userId}")
    public User getUserInfo(@PathVariable Integer userId) {
        return userService.getUserById(userId);
    }
    // 获取用户作品
    @GetMapping("/{userId}/works")
    public List<Work> getUserWorksByUserId(@PathVariable Integer userId) {
        return userService.getUserWorksByUserId(userId);
    }
    //删除用户
    @DeleteMapping("/{userId}")
    public String deleteUser(@PathVariable Integer userId) {
        userService.deleteUser(userId);
        return "删除成功！";
    }
}